package com.ruoyi.wlxz.util;

import com.kennycason.kumo.WordFrequency;
import com.kennycason.kumo.nlp.FrequencyAnalyzer;
import com.kennycason.kumo.nlp.tokenizers.ChineseWordTokenizer;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 词云生成服务类
 * Word Cloud Generation Service Class
 * 用于生成基于中文文本的词云图片
 * Used to generate word cloud images based on Chinese text
 */
@Component
public class WordCloud {
    /**
     * 验证词语是否有效
     * Validate if a word is valid
     *
     * @param word 待验证的词语 Word to be validated
     * @return 是否为有效词语 Whether the word is valid
     */
    private boolean isValidWord(String word) {
        // 过滤纯数字
        // Filter out pure numbers
        if (word.matches("\\d+")) {
            return false;
        }
        // 过滤长度小于2的词
        // Filter out words shorter than 2 characters
        if (word.length() < 2) {
            return false;
        }
        // 过滤包含特殊字符的词（只允许中英文和数字）
        // Filter out words containing special characters (only Chinese characters, English letters and numbers are allowed)
        if (word.matches(".*[^a-zA-Z0-9\\u4e00-\\u9fa5].*")) {
            return false;
        }
        return true;
    }

    /**
     * 分词即可
     *
     * @param list
     * @return
     * @throws IOException
     */
    public List<WordFrequency> generateFromText(List<String> list, Set<String> stopWords) throws IOException {
//        String pngOutputPath = "ruoyi-admin/src/main/resources/wordcloudImg/output.png";
//        String shapePicPath = "ruoyi-admin/src/main/resources/wordcloudImg/img.png";
        // 创建词频分析器
        // Create frequency analyzer
        final FrequencyAnalyzer frequencyAnalyzer = new FrequencyAnalyzer();
        // 设置停用词
        // Set stop words
        frequencyAnalyzer.setStopWords(stopWords);
        // 设置要提取的最大词数量
        // Set maximum number of words to extract
        frequencyAnalyzer.setWordFrequenciesToReturn(100);
        // 设置最小词长度
        // Set minimum word length
        frequencyAnalyzer.setMinWordLength(2);
        // 设置中文分词器
        // Set Chinese word tokenizer
        frequencyAnalyzer.setWordTokenizer(new ChineseWordTokenizer());

        // 分析文本得到词频列表
        // Analyze text to get word frequencies
        List<WordFrequency> wordFrequencies = frequencyAnalyzer.load(list);
        // 过滤无效词语
        // Filter invalid words
        return wordFrequencies = new ArrayList<>(
                wordFrequencies.stream()
                        .filter(wf -> isValidWord(wf.getWord()))
                        .collect(Collectors.toCollection(ArrayList::new))
        );
//
//        放弃了,词云图让前端生成吧
//        // 设置词云图片尺寸
//        // Set word cloud image dimensions
//        final Dimension dimension = new Dimension(1024, (int) (1024 * ratio));
//        final com.kennycason.kumo.WordCloud wordCloud = new com.kennycason.kumo.WordCloud(dimension, CollisionMode.PIXEL_PERFECT);
//
//        // 设置词语之间的间距
//        // Set padding between words
//        wordCloud.setPadding(5);
//
//        // 设置背景为透明
//        // Set transparent background
//        wordCloud.setBackgroundColor(new Color(0, 0, 0, 0));
//        // 设置词云形状
//        // Set word cloud shape
//        wordCloud.setBackground(new PixelBoundaryBackground(shapePicPath));
//
//        // 设置词云配色方案
//        // Set word cloud color palette
//        wordCloud.setColorPalette(new ColorPalette(new Color(0x4055F1), new Color(0x405DF1),
//                new Color(0x40ADF1), new Color(0x40D1F1), new Color(0x40F1E2), new Color(0x60E8BB)));
//
//        // 设置字体为楷体
//        // Set font to KaiTi
//        java.awt.Font font2 = new java.awt.Font("楷体", 0, 80);
//        wordCloud.setKumoFont(new KumoFont(font2));
//
//        // 设置词语角度为0（水平）
//        // Set word angle to 0 (horizontal)
//        wordCloud.setAngleGenerator(new AngleGenerator(0));
//
//        // 设置字体大小范围
//        // Set font size range
//        wordCloud.setFontScalar(new SqrtFontScalar(1, 90));
//
//        // 生成词云并保存为图片
//        // Generate word cloud and save as image
//        wordCloud.build(wordFrequencies);
//        wordCloud.writeToFile(pngOutputPath);
    }
}
